var G = {
    fun: {}
};

define(
    [
        'jquery',
        'bootstrap',
        'backend',
        'table',
        'form',
        'template',
        'underscore',
        'calendar',
        'calendar-language'
    ], function ($, undefined, Backend, Table, Form, Template, Underscore, Calendar, Calendarlanguage) {

        var Controller = {
            fun: {
                bind_room_price_list: function (room_info_id, check_in_time, check_out_time) {
                    $.post('pms/pmsroomstatus/ajax_get_room_price_list', {
                            room_id       : room_info_id,
                            check_in_time : check_in_time,
                            check_out_time: check_out_time
                        },
                        function (d) {
                            // console.log(d);
                            if (d['error'] == 200) {
                                var price_json = [];
                                $('#todayBox .sum_price span').text(d['sum_price_format']);
                                $('#c-total_price').val(d['sum_price']);
                                $('#c-days').val(d['total']);

                                $('#priceBox').empty();
                                $.each(d['rows'], function (i) {
                                    var row = d['rows'][i];
                                    var special_price_flag = row['special_price'] == 1 ? '<span class="badge" title="特殊日期价格">特</span>' : '';
                                    var html = '<div class="col-xs-4 stat-col"><div class="stat-icon"><i class="fa fa-bed"></i></div><div class="stat"><div class="value">￥' + row['price'] + ' ' + special_price_flag + '</div><div class="name"> ' + row['day'] + '</div></div><div class="progress"><div class="progress-bar progress-bar-success" style="width: 30%"></div></div></div>';
                                    $('#priceBox').append(html);

                                    price_json.push({
                                        'day'          : row['day'],
                                        'price'        : row['price'],
                                        'special_price': row['special_price']
                                    });
                                });
                                price_json = price_json.length === 0 ? '' : JSON.stringify(price_json);
                                $('#c-price_json').val(price_json);
                            } else {
                                Toastr.error('住院时间不能大于出院时间');
                            }
                        }
                        , 'json'
                    );
                },
                Reload              : function () {
                    window.location.reload();
                },
                ReloadReserveTable  : function () {
                    $('.layui-layer-iframe').find('.layui-layer-close').click();
                    $('#reserve_table').bootstrapTable('refresh', {});
                },
                ReloadOrderTable    : function () {
                    $('.layui-layer-iframe').find('.layui-layer-close').click();
                    $('#order_table').bootstrapTable('refresh', {});
                }
            },

            index       : function () {
                $.each($('.btn-context'), function (i) {
                    var that = $('.btn-context').eq(i);
                    var room = $.trim(that.parents('.box').find('.box-header h4').text());
                    var id = that.data('id');
                    var room_no = that.data('room_no');
                    var room_status = that.data('room_status');
                    var is_dirty = that.data('is_dirty');
                    var is_repair = that.data('is_repair');
                    var is_lock = that.data('is_lock');

                    var title = '<span data-id="' + id + '" class="js_detail">' + that.data('title') + ':' + room_no + '</span><a href="javascript:;" class="pull-right js_calendar" data-id="' + id + '" data-room_no="' + room_no + '"><i class="fa fa-calendar-check-o"></i> 房态日历</a>';

                    var html = '';
                    html += '<div class="row context-menu" data-id="' + id + '" data-room_no="' + room_no + '">';
                    html += '<div class="col-xs-12">';
                    // html += '<a href="javascript:;" class="btn btn-success" data-event="reserve"><i class="fa fa-book"></i> 预定房间</a> ';
                    html +=
                        `<a href="javascript:;" class="btn btn-info" data-event="checkin" data-room="${room}" style="margin-right:3px;"><i class="fa fa-user"></i> 现场预约</a>`;
                    // html += '<a href="javascript:;" class="btn btn-info" data-event="pay"><i class="fa fa-money"></i> 收款</a> ';
                    html +=
                        '<a href="javascript:;" class="btn btn-info" data-event="checkout"><i class="fa fa-sign-out"></i> 出院结算</a>';
                    html += '</div>';
                    html += '<div class="col-xs-12">';
                    html +=
                        '<a href="javascript:;" class="btn btn-default" data-event="lock"><i class="fa fa-lock"></i> 设为锁床</a> ';
                    html +=
                        '<a href="javascript:;" class="btn btn-success" data-event="unlock"><i class="fa fa-unlock"></i> 解锁床</a> ';
                    html +=
                        '<a href="javascript:;" class="btn btn-default" data-event="dirty"><i class="fa fa-meh-o"></i> 设为脏床</a> ';
                    html +=
                        '<a href="javascript:;" class="btn btn-success" data-event="clean"><i class="fa fa-smile-o"></i> 设为干净床</a> ';
                    html +=
                        '<a href="javascript:;" class="btn btn-default" data-event="repair"><i class="fa fa-wrench"></i> 设为维修</a> ';
                    html +=
                        '<a href="javascript:;" class="btn btn-success" data-event="repaired"><i class="fa fa-wrench"></i> 维修完毕</a>'

                    html += '</div>';

                    html += '</div>';

                    var content = $(html);

                    if (room_status == '0') {
                        content.find('a[data-event="pay"],a[data-event="checkout"]').remove();
                    } else {
                        // content.find('a[data-event="checkin"]').remove();
                    }
                    html += ' </div>';

                    html += '<div class="col-xs-12">';
                    if (is_lock == '0') {
                        content.find('a[data-event="unlock"]').remove();
                    } else {
                        // content.find('a[data-event="reserve"],a[data-event="pay"],a[data-event="checkout"]').remove();
                        content.find('a[data-event="lock"],a[data-event="dirty"],a[data-event="clean"],a[data-event="repair"],a[data-event="repaired"]').remove();
                    }

                    if (is_dirty == '0') {
                        content.find('a[data-event="clean"]').remove();
                    } else {
                        content.find('a[data-event="reserve"]').remove();
                        content.find('a[data-event="checkin"]').remove();
                        content.find('a[data-event="dirty"]').remove();
                    }

                    if (is_repair == '0') {
                        content.find('a[data-event="repaired"]').remove();
                    } else {
                        content.find('a[data-event="repair"]').remove();
                    }

                    that.popover({
                        trigger  : 'hover',
                        placement: 'top',
                        html     : true,
                        delay    : {hide: 100},
                        title    : title,
                        content  : content
                    });
                });

                $('.btn-context').on('shown.bs.popover', function (event) {
                    var that = this;
                    $(this).parent().find('div.popover').on('mouseenter', function () {
                        $(that).attr('in', true);
                    }).on('mouseleave', function () {
                        $(that).removeAttr('in');
                        $(that).popover('hide');
                    });
                }).on('hide.bs.popover', function (event) {
                    if ($(this).attr('in')) {
                        event.preventDefault();
                    }
                }).on('shown.bs.popover', function (event) {
                    var that = $(this);
                    var id = that.data('id');
                    var order_id = that.data('order_id');
                    var room_no = that.data('room_no');
                    var popover_id = that.attr('aria-describedby');

                    if (order_id == 0) {
                        var obj = $('#' + popover_id).find('h3.popover-title span.js_detail');
                        obj.css({
                            'text-decoration': 'none',
                            'cursor'         : 'text',
                            'color'          : '#111'
                        });
                    } else {
                        var obj = $('#' + popover_id).find('h3.popover-title span.js_detail');
                        obj.html('查看订单<i class="fa fa-hand-o-right"></i> (' + obj.text() + ')');
                    }

                    var calendar = $('#' + popover_id).find('h3.popover-title a.js_calendar');
                    calendar.attr('href', 'javascript:;')//.data('id', id).data('room_no', room_no);

                    $('h3.popover-title span.js_detail').unbind('click').click(function () {
                        var id = $(that).data('order_id');
                        let param = $(that).data();
                        console.log(param);
                        if (id > 0) {
                            var url = 'pms/pmsroomstatus/order_detail?id=' + id;
                            $(this).data('area', ['75%', '85%']);
                            Fast.api.open(url, `预约详情(${param.room}房间${param.room_no}床)`, $(this).data() || {});
                        }
                    });

                    $('h3.popover-title a.js_calendar').unbind('click').click(function () {
                        var id = $(that).data('id');
                        var room_no = $(that).data('room_no');
                        var url = 'pms/pmsroomstatus/calendar?id=' + id;
                        $(this).data('area', ['60%', '80%']);
                        Fast.api.open(url, '房态日历(床号：' + room_no + ')', $(this).data() || {});
                    });

                    $('.context-menu a').unbind('click').click(function () {
                        var that = $(this);
                        var context = that.parents('.context-menu').eq(0);
                        var orderEl = that.parents('.col-md-2').find('a').eq(0);
                        var id = context.data('id');
                        var order_id = orderEl.data('order_id');

                        var room_no = context.data('room_no');
                        var event = that.data('event');
                        var start_date = $('#search_start_date').val().trim();
                        var end_date = $('#search_end_date').val().trim();
                        var room = that.data('room');
                        // console.log(id, event);

                        switch (event) {
                            case 'reserve':
                                var url = 'pms/pmsroomstatus/reserve?id=' + id + '&start_date=' + start_date + '&end_date=' + end_date;
                                $(this).data('area', ['55%', '85%']);
                                Fast.api.open(url, '预定(床号：' + room_no + ')', $(this).data() || {});
                                break;

                            case 'checkin':
                                var url = 'pms/pmsroomstatus/checkin?id=' + id;
                                $(this).data('area', ['55%', '85%']);
                                Fast.api.open(url, `现场预约(${room} ${room_no}床)`, $(this).data() || {});
                                break;

                            case 'pay':
                                var url = 'pms/pmsroomstatus/pay?id=' + id;
                                $(this).data('area', ['55%', '70%']);
                                Fast.api.open(url, '收款(床号：' + room_no + ')', $(this).data() || {});
                                break;

                            case 'checkout':
                                var url = 'pms/pmsroomstatus/checkout?id=' + order_id;
                                $(this).data('area', ['70%', '60%']);
                                Fast.api.open(url, '出院(床号：' + room_no + ')', $(this).data() || {});
                                break;

                            case 'calendar':
                                var url = 'pms/pmsroomstatus/calendar?id=' + id;
                                $(this).data('area', ['60%', '80%']);
                                Fast.api.open(url, '房态日历(床号：' + room_no + ')', $(this).data() || {});
                                break;
                        }

                        if (event == 'lock' || event == 'unlock' || event == 'clean' || event == 'dirty' || event == 'repair' || event == 'repaired') {
                            var msg = '';
                            switch (event) {
                                case 'lock':
                                    msg = '确认锁床(床号：' + room_no + ')';
                                    break;
                                case 'unlock':
                                    msg = '确认解锁床(床号：' + room_no + ')';
                                    break;
                                case 'clean':
                                    msg = '确认设为净床(床号：' + room_no + ')';
                                    break;
                                case 'dirty':
                                    msg = '确认设为脏床(床号：' + room_no + ')';
                                    break;
                                case 'repair':
                                    msg = '确认设为维修床(床号：' + room_no + ')';
                                    break;
                                case 'repaired':
                                    msg = '确认维修好(床号：' + room_no + ')';
                                    break;
                            }

                            Layer.confirm(msg, {
                                icon : 3,
                                title: '提示'
                            }, function (index) {
                                Backend.api.ajax({
                                    url : 'pms/Pmsroomstatus/ajax_set_room',
                                    data: {id: id, status: event}
                                }, function (d) {
                                    Layer.close(index);
                                    setTimeout(function () {
                                        window.location.reload();
                                    }, 1000);
                                });
                            });
                        }

                    });
                });

                // 初始化表格参数配置
                Table.api.init({
                    extend: {
                        index_url: 'pms/pmsreserveinfo/index' + location.search,
                        table    : 'pms_reserve_info'
                    }
                });

                var reserve_table = $('#reserve_table');

                //双击编辑
                $(reserve_table).unbind('dblclick').on('dblclick', 'tr', function (e) {
                    e.preventDefault();
                    var that = $(this);
                    that.find('a.js_reserve_detail').click();
                });

                //在普通搜索渲染后
                reserve_table.on('post-common-search.bs.table', function (event, table) {
                    var form = $('form', table.$commonsearch);
                    $('input[name=\'room_info_id\']', form).addClass('selectpage').data('source', 'pms/pmsroominfo/selectpage').data('primaryKey', 'id').data('field', 'room_no');
                    Form.events.cxselect(form);
                    Form.events.selectpage(form);
                });

                // 初始化表格
                reserve_table.bootstrapTable({
                    url              : $.fn.bootstrapTable.defaults.extend.index_url,
                    pk               : 'id',
                    sortName         : 'id',
                    searchFormVisible: true,
                    search           : false,
                    showToggle       : false,
                    showExport       : false,
                    showColumns      : false,
                    columns          : [
                        [
                            {field: 'id', title: __('Id'), operate: false},
                            {
                                field: 'reserve_no', title: __('预定号'), formatter: function (value, row, index) {
                                    return value + ' <span class="label label-success">' + row['source'] + '</span>';
                                }, operate                                      : 'LIKE'
                            },
                            {field: 'source', title: __('来源'), visible: false},
                            {
                                field: 'realname', title: __('联系人'), formatter: function (value, row, index) {
                                    var sex_name = '女士';
                                    var sex_class = 'label-danger';
                                    if (row['sex'] == 1) {
                                        sex_name = '先生';
                                        sex_class = 'label-info';
                                    }
                                    return row['realname'] + ' <label class="label ' + sex_class + '">' + sex_name + '</label>';
                                }, operate                                    : 'LIKE'
                            },
                            {field: 'tel', title: __('联系电话'), operate: 'LIKE'},
                            {field: 'check_in_time', title: __('住院时间'), operate: false, addclass: 'datetimerange', formatter: Table.api.formatter.datetime},
                            {field: 'check_out_time', title: __('出院时间'), operate: false, addclass: 'datetimerange', formatter: Table.api.formatter.datetime},
                            {field: 'days', title: __('天数'), operate: false},
                            {
                                field: 'room_info_id', title: __('房间'), formatter: function (value, row, index) {
                                    return '<span class="label label-primary">' + row['room_type_name'] + '</span><br />' + row['room_no'] + '房';
                                }
                            },
                            // {field: 'total_price', title: __('总房费'), operate: false},
                            {
                                field: 'reserve_status', title: __('状态'), formatter: function (value, row, index) {
                                    var html = '';
                                    switch (value) {
                                        case 0:
                                            html = '<span class="text-info"><i class="fa fa-circle"></i> 新预定</span>';
                                            break;
                                        case 1:
                                            html =
                                                '<span class="text-success"><i class="fa fa-circle"></i> 已转订单</span>';
                                            break;
                                        case -1:
                                            html = '<span class="text-danger"><i class="fa fa-circle"></i> 作废预定</span>';
                                            break;
                                    }
                                    return html;
                                }
                            },
                            {field: 'updatetime', title: __('Updatetime'), operate: false, addclass: 'datetimerange', formatter: Table.api.formatter.datetime},
                            {field: 'last_editor_nickname', title: __('最后更新人'), operate: false},
                            {
                                field: 'operate', title: __('Operate'), table: reserve_table, events: Table.api.events.operate, formatter: function (value, row, index) {
                                    if (row['reserve_status'] == 0) {
                                        return '<a href="javascript:;" class="btn btn-xs btn-info js_reserve_detail" data-id="' + row['id'] + '" data-room_no="' + row['room_no'] + '"><i class="fa fa-file-text-o"></i> 查看</a> ';
                                    } else if (row['reserve_status'] == -1) {
                                        return '<span class="text-default" data-toggle="tooltip" data-original-title="' + row['cancel_remarks'] + '"><i class="fa fa-circle"></i> 作废理由</span>';
                                    }
                                }
                            }
                        ]
                    ]
                });

                // 编辑按钮事件
                $(reserve_table).on('click', 'a.js_reserve_detail', function (e) {
                    e.preventDefault();
                    var id = $(this).data('id');
                    var room_no = $(this).data('room_no');

                    var url = 'pms/pmsroomstatus/reserve_detail?id=' + id;
                    $(this).data('area', ['55%', '85%']);
                    Fast.api.open(url, '预定详情(床号：' + room_no + ')', $(this).data() || {});
                });

                // 为表格绑定事件
                Table.api.bindevent(reserve_table);

                Controller.api.bindevent();


                //快速查询空房
                $('#js_SearchRoom').click(function () {
                    var search_start_date = $('#search_start_date').val().trim();
                    var search_end_date = $('#search_end_date').val().trim();

                    if (search_start_date.length == 0 || search_end_date.length == 0) {
                        Layer.msg('提示：住院时间和出院时间不能为空');
                    } else {
                        location.href =
                            '?t=search_room&start_date=' + search_start_date + '&end_date=' + search_end_date;
                    }
                })
            },
            checkin     : function () {
                // 初始化表格参数配置
                Table.api.init({
                    extend: {
                        table: 'pms_room_info'
                    }
                });

                var customer_table = $('#customer_table');

                // 初始化表格
                customer_table.bootstrapTable({
                    pk          : 'id',
                    sortName    : 'id',
                    search      : false,
                    showToggle  : false,
                    showExport  : false,
                    commonSearch: false,
                    showColumns : false,
                    pagination  : false,
                    columns     : [
                        [
                            {
                                title: __('#'), formatter: function (value, row, index) {
                                    return (index + 1);
                                }
                            },
                            {
                                field: 'realname', title: __('入住姓名'), formatter: function (value, row, index) {
                                    var sexLabel = '<span class="label label-danger">女士</span>';
                                    if (row['sex'] == 1) {
                                        sexLabel = '<span class="label label-info">先生</span>';
                                    }

                                    return value + ' ' + sexLabel;
                                }
                            },
                            {
                                field: 'person_no', title: __('证件号码'), formatter: function (value, row, index) {
                                    return value + ' <span class="label label-primary">' + row['certificates_type'] + '</span>';
                                }
                            },
                            {field: 'tel', title: __('联系电话')},
                            {
                                field: 'operate', title: __('Operate'), formatter: function (value, row, index) {
                                    return '<a href="javascript:;" class="btn btn-xs btn-success js_edit" data-toggle="tooltip" data-original-title="编辑" data-index="' + index + '"><i class="fa fa-pencil"></i></a> <a href="javascript:;" class="btn btn-xs btn-danger js_delete" data-toggle="tooltip" data-original-title="删除" data-index="' + index + '"><i class="fa fa-trash"></i></a>';
                                }
                            }
                        ]
                    ]
                });

                //添加同住客人
                $('#js_MAdd').click(function () {
                    $('#customerModal').modal('show');
                    $('#m-index').val(-1);
                    $('#m-sex option').removeAttr('selected');
                    $('#m-realname, #m-person_no, #m-birthday, #m-tel').val('');
                });

                // 编辑按钮事件
                $(customer_table).on('click', '[data-index].js_edit', function (e) {
                    e.preventDefault();
                    var data = customer_table.bootstrapTable('getData');
                    var index = $(this).data('index');
                    var row = data[index];
                    // console.log('edit', row);
                    $('#customerModal').modal('show');

                    $('#m-index').val(index);
                    $('#m-sex option[value="' + row['sex'] + '"]').prop('selected', 'selected');
                    $('#m-realname').val(row['realname']);
                    $('#m-person_no').val(row['person_no']);
                    $('#m-birthday').val(row['birthday']);
                    $('#m-tel').val(row['tel']);
                });

                // 删除按钮事件
                $(customer_table).on('click', '[data-index].js_delete', function (e) {
                    e.preventDefault();
                    var data = customer_table.bootstrapTable('getData');
                    var delete_index = $(this).data('index');
                    // console.log('delete', data[delete_index]);

                    Layer.confirm('确认删除此客人', {
                        icon : 3,
                        title: '提示'
                    }, function (x) {
                        var new_data = [];
                        $.each(data, function (i) {
                            if (i !== delete_index) {
                                new_data.push(data[i]);
                            }
                        });
                        // console.log(new_data);
                        customer_table.bootstrapTable('load', {total: new_data.length, rows: new_data});

                        new_data = !new_data.length ? '' : new_data;
                        $('#c-customer_data').val(JSON.stringify(new_data));
                        Layer.close(x);
                    });
                });

                //保存编辑的入住客人信息
                $('#js_MSubmit').click(function () {
                    $('#customerModal').modal('hide');
                    var data = customer_table.bootstrapTable('getData');
                    var index = $('#m-index').val();
                    // console.log(index)
                    if (index == -1) {
                        index = data.length;
                        data.push({
                            'index'            : data.length,
                            'sex'              : $('#m-sex').val(),
                            'realname'         : $('#m-realname').val(),
                            'certificates_type': $('#m-certificates_type').val(),
                            'person_no'        : $('#m-person_no').val(),
                            'birthday'         : $('#m-birthday').val(),
                            'tel'              : $('#m-tel').val()
                        });
                    } else {
                        data[index]['sex'] = $('#m-sex').val();
                        data[index]['realname'] = $('#m-realname').val();
                        data[index]['certificates_type'] = $('#m-certificates_type').val();
                        data[index]['person_no'] = $('#m-person_no').val();
                        data[index]['birthday'] = $('#m-birthday').val();
                        data[index]['tel'] = $('#m-tel').val();
                    }

                    customer_table.bootstrapTable('load', {total: data.length, rows: data});
                    // console.log(data);
                    $('#c-customer_data').val(JSON.stringify(data));
                });

                // 为表格绑定事件
                Table.api.bindevent(customer_table);

                $('#js_getBirthday').click(function () {
                    if ($('#c-person_no').val() == '') {
                        Layer.msg('证件号码不能为空');
                    } else {
                        var birthday = '';
                        var person_no = $('#c-person_no').val();
                        if (person_no.length == 15) {
                            birthday = '19' + person_no.substr(6, 6);
                        } else if (person_no.length == 18) {
                            birthday = person_no.substr(6, 8);
                        }

                        birthday = birthday.replace(/(.{4})(.{2})/, '$1-$2-');

                        if (birthday == '') {
                            Layer.msg('读取出错');
                        } else {
                            $('#c-birthday').val(birthday);
                        }
                    }
                });

                $('#js_getMBirthday').click(function () {
                    if ($('#m-person_no').val() == '') {
                        Layer.msg('证件号码不能为空');
                    } else {
                        var birthday = '';
                        var person_no = $('#m-person_no').val();
                        if (person_no.length == 15) {
                            birthday = '19' + person_no.substr(6, 6);
                        } else if (person_no.length == 18) {
                            birthday = person_no.substr(6, 8);
                        }

                        birthday = birthday.replace(/(.{4})(.{2})/, '$1-$2-');

                        if (birthday == '') {
                            Layer.msg('读取出错');
                        } else {
                            $('#m-birthday').val(birthday);
                        }
                    }
                });


                $('#c-check_out_time').on('dp.change', function (e) {
                    // console.log($(this).val());
                    var room_info_id = $('#c-room_info_id').val();
                    var check_in_time = $('#c-check_in_time').val();
                    var check_out_time = $('#c-check_out_time').val();

                    Controller.fun.bind_room_price_list(room_info_id, check_in_time, check_out_time);
                });


                $('#tab a').on('shown.bs.tab', function (e) {
                    if (e.currentTarget.attributes[1]['textContent'] == 'customer') {
                        var sex = $('#c-sex').val();
                        var realname = $('#c-realname').val();
                        var certificates_type = $('#c-certificates_type').val();
                        var person_no = $('#c-person_no').val();
                        var birthday = $('#c-birthday').val();
                        var tel = $('#c-tel').val();

                        if (realname == '') {
                            Layer.msg('请先录入【联系人姓名】');
                            $('#tab a:eq(0)').tab('show')
                        } else {
                            var data = customer_table.bootstrapTable('getData');
                            if (data.length == 0) {
                                var data = [{sex: sex, realname: realname, certificates_type: certificates_type, person_no: person_no, birthday: birthday, tel: tel}];
                                customer_table.bootstrapTable('load', {total: 1, rows: data});
                                $('#c-customer_data').val(JSON.stringify(data));
                            }
                        }
                    }
                });

                Controller.api.bindevent();
                Form.api.bindevent($('form[role=customerform]'));

                //提交预定/入住后刷新
                Form.api.bindevent('form', function (data, ret) {
                    parent.window.G.fun.Reload();
                });

            },
            reserve     : function () {
                // 初始化表格参数配置
                Table.api.init({
                    extend: {
                        table: 'pms_room_info'
                    }
                });

                var customer_table = $('#customer_table');

                // 初始化表格
                customer_table.bootstrapTable({
                    pk          : 'id',
                    sortName    : 'id',
                    search      : false,
                    showToggle  : false,
                    showExport  : false,
                    commonSearch: false,
                    showColumns : false,
                    pagination  : false,
                    columns     : [
                        [
                            {
                                title: __('#'), formatter: function (value, row, index) {
                                    return (index + 1);
                                }
                            },
                            {
                                field: 'realname', title: __('入住姓名'), formatter: function (value, row, index) {
                                    var sexLabel = '<span class="label label-danger">女士</span>';
                                    if (row['sex'] == 1) {
                                        sexLabel = '<span class="label label-info">先生</span>';
                                    }

                                    return value + ' ' + sexLabel;
                                }
                            },
                            {
                                field: 'person_no', title: __('证件号码'), formatter: function (value, row, index) {
                                    return value + ' <span class="label label-primary">' + row['certificates_type'] + '</span>';
                                }
                            },
                            {field: 'tel', title: __('联系电话')},
                            {
                                field: 'operate', title: __('Operate'), formatter: function (value, row, index) {
                                    return '<a href="javascript:;" class="btn btn-xs btn-success js_edit" data-toggle="tooltip" data-original-title="编辑" data-index="' + index + '"><i class="fa fa-pencil"></i></a> <a href="javascript:;" class="btn btn-xs btn-danger js_delete" data-toggle="tooltip" data-original-title="删除" data-index="' + index + '"><i class="fa fa-trash"></i></a>';
                                }
                            }
                        ]
                    ]
                });

                //当表格数据加载完成时
                customer_table.on('load-success.bs.table', function (e, data) {

                });

                //添加同住客人
                $('#js_MAdd').click(function () {
                    $('#customerModal').modal('show');
                    $('#m-index').val(-1);
                    $('#m-sex option').removeAttr('selected');
                    $('#m-realname, #m-person_no, #m-birthday, #m-tel').val('');
                });

                // 编辑按钮事件
                $(customer_table).on('click', '[data-index].js_edit', function (e) {
                    e.preventDefault();
                    var data = customer_table.bootstrapTable('getData');
                    var index = $(this).data('index');
                    var row = data[index];
                    // console.log('edit', row);
                    $('#customerModal').modal('show');

                    $('#m-index').val(index);
                    $('#m-sex option[value="' + row['sex'] + '"]').prop('selected', 'selected');
                    $('#m-realname').val(row['realname']);
                    $('#m-person_no').val(row['person_no']);
                    $('#m-birthday').val(row['birthday']);
                    $('#m-tel').val(row['tel']);
                });

                // 删除按钮事件
                $(customer_table).on('click', '[data-index].js_delete', function (e) {
                    e.preventDefault();
                    var data = customer_table.bootstrapTable('getData');
                    var delete_index = $(this).data('index');
                    // console.log('delete', data[delete_index]);

                    Layer.confirm('确认删除此客人', {
                        icon : 3,
                        title: '提示'
                    }, function (x) {
                        var new_data = [];
                        $.each(data, function (i) {
                            if (i != delete_index) {
                                new_data.push(data[i]);
                            }
                        });
                        // console.log(new_data);
                        customer_table.bootstrapTable('load', {total: new_data.length, rows: new_data});

                        new_data = new_data.length == 0 ? '' : new_data;
                        $('#c-customer_data').val(JSON.stringify(new_data));
                        Layer.close(x);
                    });
                });

                //保存编辑的入住客人信息
                $('#js_MSubmit').click(function () {
                    $('#customerModal').modal('hide');
                    var data = customer_table.bootstrapTable('getData');
                    var index = $('#m-index').val();
                    // console.log(index)
                    if (index == -1) {
                        index = data.length;
                        data.push({
                            'index'            : data.length,
                            'sex'              : $('#m-sex').val(),
                            'realname'         : $('#m-realname').val(),
                            'certificates_type': $('#m-certificates_type').val(),
                            'person_no'        : $('#m-person_no').val(),
                            'birthday'         : $('#m-birthday').val(),
                            'tel'              : $('#m-tel').val()
                        });
                    } else {
                        data[index]['sex'] = $('#m-sex').val();
                        data[index]['realname'] = $('#m-realname').val();
                        data[index]['certificates_type'] = $('#m-certificates_type').val();
                        data[index]['person_no'] = $('#m-person_no').val();
                        data[index]['birthday'] = $('#m-birthday').val();
                        data[index]['tel'] = $('#m-tel').val();
                    }

                    customer_table.bootstrapTable('load', {total: data.length, rows: data});
                    // console.log(data);
                    $('#c-customer_data').val(JSON.stringify(data));
                });

                // 为表格绑定事件
                Table.api.bindevent(customer_table);

                $('#js_getBirthday').click(function () {
                    if ($('#c-person_no').val() == '') {
                        Layer.msg('证件号码不能为空');
                    } else {
                        var birthday = '';
                        var person_no = $('#c-person_no').val();
                        if (person_no.length == 15) {
                            birthday = '19' + person_no.substr(6, 6);
                        } else if (person_no.length == 18) {
                            birthday = person_no.substr(6, 8);
                        }

                        birthday = birthday.replace(/(.{4})(.{2})/, '$1-$2-');

                        if (birthday == '') {
                            Layer.msg('读取出错');
                        } else {
                            $('#c-birthday').val(birthday);
                        }
                    }
                });

                $('#js_getMBirthday').click(function () {
                    if ($('#m-person_no').val() == '') {
                        Layer.msg('证件号码不能为空');
                    } else {
                        var birthday = '';
                        var person_no = $('#m-person_no').val();
                        if (person_no.length == 15) {
                            birthday = '19' + person_no.substr(6, 6);
                        } else if (person_no.length == 18) {
                            birthday = person_no.substr(6, 8);
                        }

                        birthday = birthday.replace(/(.{4})(.{2})/, '$1-$2-');

                        if (birthday == '') {
                            Layer.msg('读取出错');
                        } else {
                            $('#m-birthday').val(birthday);
                        }
                    }
                });
                /* $('#c-check_in_time, #c-check_out_time').on('dp.change', function (e) {
                     // console.log($(this).val());
                     var room_info_id = $('#c-room_info_id').val();
                     var check_in_time = $('#c-check_in_time').val();
                     var check_out_time = $('#c-check_out_time').val();

                     Controller.fun.bind_room_price_list(room_info_id, check_in_time, check_out_time);
                 });*/

                $('#tab a').on('shown.bs.tab', function (e) {
                    if (e.currentTarget.attributes[1]['textContent'] == 'customer') {
                        var sex = $('#c-sex').val();
                        var realname = $('#c-realname').val();
                        var certificates_type = $('#c-certificates_type').val();
                        var person_no = $('#c-person_no').val();
                        var birthday = $('#c-birthday').val();
                        var tel = $('#c-tel').val();

                        if (realname == '') {
                            Layer.msg('请先录入【联系人姓名】');
                            $('#tab a:eq(0)').tab('show')
                        } else {
                            var data = customer_table.bootstrapTable('getData');
                            if (data.length == 0) {
                                var data = [{sex: sex, realname: realname, certificates_type: certificates_type, person_no: person_no, birthday: birthday, tel: tel}];
                                customer_table.bootstrapTable('load', {total: 1, rows: data});
                                $('#c-customer_data').val(JSON.stringify(data));
                            }
                        }
                    }
                });

                Controller.api.bindevent();

                //提交预定/入住后刷新
                Form.api.bindevent('form', function (data, ret) {
                    parent.window.G.fun.Reload();
                });
            },
            calendar    : function () {
                var room_id = $('#c-room_id').val();
                var NowDate = new Date();
                var NowYear = NowDate.getFullYear();
                var NowMonth = NowDate.getMonth() + 1;
                var NowMonth = NowDate.getMonth() + 1, NowMonth = NowMonth < 10 ? '0' + NowMonth : NowMonth;
                var NowDay = NowDate.getDate(), NowDay = NowDay < 10 ? '0' + NowDay : NowDay;
                var day = NowYear + '-' + NowMonth + '-' + NowDay;

                var calendar = $('#calendar').calendar({
                    events_source       : 'pms/pmsroomstatus/ajax_get_room_status_calendar?room_id=' + room_id,
                    view                : 'month',
                    tmpl_path           : '/assets/addons/pms/libs/bootstrap-calendar/tmpls/',
                    tmpl_cache          : false,
                    weekbox             : false,
                    display_week_numbers: false,
                    day                 : day,
                    language            : 'zh-CN',
                    onAfterEventsLoad   : function (events) {
                        if (!events) {
                            return;
                        }
                    },
                    onAfterViewLoad     : function (view) {
                        $('.page-header h3').text(this.getTitle());
                        $('.btn-group button').removeClass('active');
                        $('button[data-calendar-view="' + view + '"]').addClass('active');
                    },
                    classes             : {
                        months: {
                            general: 'label'
                        }
                    }
                });


                $('.btn-group button[data-calendar-nav]').each(function () {
                    var $this = $(this);
                    $this.click(function () {
                        calendar.navigate($this.data('calendar-nav'));
                    });
                });

                $('.btn-group button[data-calendar-view]').each(function () {
                    var $this = $(this);
                    $this.click(function () {
                        calendar.view($this.data('calendar-view'));
                    });
                });

                $('#first_day').change(function () {
                    var value = $(this).val();
                    value = value.length ? parseInt(value) : null;
                    calendar.setOptions({first_day: value});
                    calendar.view();
                });

                $('#language').change(function () {
                    calendar.setLanguage($(this).val());
                    calendar.view();
                });

                $('#events-in-modal').change(function () {
                    var val = $(this).is(':checked') ? $(this).val() : null;
                    calendar.setOptions({modal: val});
                });
                $('#format-12-hours').change(function () {
                    var val = $(this).is(':checked') ? true : false;
                    calendar.setOptions({format12: val});
                    calendar.view();
                });
                $('#show_wbn').change(function () {
                    var val = $(this).is(':checked') ? true : false;
                    calendar.setOptions({display_week_numbers: val});
                    calendar.view();
                });
                $('#show_wb').change(function () {
                    var val = $(this).is(':checked') ? true : false;
                    calendar.setOptions({weekbox: val});
                    calendar.view();
                });
                $('#events-modal .modal-header, #events-modal .modal-footer').click(function (e) {
                    //e.preventDefault();
                    //e.stopPropagation();
                });
            },
            order_detail: function () {
                $('#m-customer_data').val(JSON.stringify(customer_data));

                // 初始化表格参数配置
                Table.api.init({
                    extend: {
                        table: 'pms_order_people_list'
                    }
                });

                var pay_table = $('#pay_table');

                pay_table.on('post-body.bs.table', function (data) {
                    $('.js_deleteItems').click(function () {
                        var that = $(this);
                        var title = that.data('title');
                        var event = that.data('type');
                        $('#editModal #m-event').val('delete-' + event);
                        $('#editModal .btn-primary').attr('data-items_id', that.data('id'));

                        $('#editModal').modal('show');
                        $('#editModal #editModalLabel').text('删除消费项目 - ' + title);
                        $('#m-edit-linkman').hide();
                        $('#m-edit-date').hide();
                        $('#m-edit-addons').hide();
                        $('#m-edit-customer').hide();
                    });
                });

                // 初始化表格
                pay_table.bootstrapTable({
                    data        : pay_data['rows'],
                    pk          : 'id',
                    sortName    : 'id',
                    search      : false,
                    showToggle  : false,
                    showExport  : false,
                    commonSearch: false,
                    showColumns : false,
                    pagination  : false,
                    columns     : [
                        [
                            {
                                title: __('#'), formatter: function (value, row, index) {
                                    return (index + 1);
                                }
                            },
                            {
                                field: 'name', title: __('项目名称'), align: 'left', formatter(value, row, index) {
                                    var html = row['remarks'].length == 0 ? value : '<a href="#" data-toggle="tooltip" data-placement="top" title="备注:' + row['remarks'] + '">' + value + '</a>';
                                    return html;
                                }
                            },
                            {
                                field: 'money', title: __('金额'), formatter: function (value, row, index) {
                                    var valueClass = value >= 0 ? 'label-success' : 'label-danger';
                                    return '<span class="label ' + valueClass + '">￥' + value + '</span>';
                                }
                            },
                            {field: 'createtime', title: __('创建时间'), operate: false, addclass: 'datetimerange', formatter: Table.api.formatter.datetime},
                            {field: 'creator_nickname', title: __('操作员'), operate: false},
                            {
                                field: 'type', title: __('操作'), formatter: function (value, row, index) {
                                    if (value == 'roomitems' || value == 'servicesitems') {
                                        return '<a href="javascript:;" class="btn btn-xs btn-danger js_deleteItems" data-toggle="tooltip" title="删除" data-original-title="删除" data-type="' + row['type'] + '" data-id="' + row['id'] + '" data-title="' + row['name'] + '"><i class="fa fa-trash"></i></a>';
                                    } else {
                                        return '-';
                                    }
                                }
                            }
                        ]
                    ]
                });

                var customer_table = $('#customer_table');

                // 初始化表格
                customer_table.bootstrapTable({
                    data        : customer_data,
                    pk          : 'id',
                    sortName    : 'id',
                    search      : false,
                    showToggle  : false,
                    showExport  : false,
                    commonSearch: false,
                    showColumns : false,
                    pagination  : false,
                    columns     : [
                        [
                            {
                                title: __('#'), formatter: function (value, row, index) {
                                    return (index + 1);
                                }
                            },
                            {
                                field: 'realname', title: __('入住姓名'), formatter: function (value, row, index) {
                                    var sexLabel = '<span class="label label-danger">女士</span>';
                                    if (row['sex'] == 1) {
                                        sexLabel = '<span class="label label-info">先生</span>';
                                    }

                                    return value + ' ' + sexLabel;
                                }
                            },
                            {
                                field: 'person_no', title: __('证件号码'), formatter: function (value, row, index) {
                                    return value + ' <span class="label label-primary">' + row['certificates_type'] + '</span>';
                                }
                            },
                            {field: 'tel', title: __('联系电话')},
                            {
                                field: 'operate', title: __('Operate'), formatter: function (value, row, index) {
                                    return '<a href="javascript:;" class="btn btn-xs btn-success js_edit" data-toggle="tooltip" data-original-title="编辑" data-index="' + index + '"><i class="fa fa-pencil"></i></a> <a href="javascript:;" class="btn btn-xs btn-danger js_delete" data-toggle="tooltip" data-original-title="删除" data-index="' + index + '"><i class="fa fa-trash"></i></a>';
                                }
                            }
                        ]
                    ]
                });

                //添加同住客人
                $('#js_MAdd').click(function () {
                    $('#customerModal').modal('show');
                    $('#mm-index').val(-1);
                    $('#mm-sex option').removeAttr('selected');
                    $('#mm-realname, #mm-person_no, #mm-birthday, #mm-tel').val('');
                });

                // 编辑按钮事件
                $(customer_table).on('click', '[data-index].js_edit', function (e) {
                    e.preventDefault();
                    var data = customer_table.bootstrapTable('getData');
                    var index = $(this).data('index');
                    var row = data[index];
                    // console.log('edit', row);
                    $('#customerModal').modal('show');

                    $('#mm-index').val(index);
                    $('#mm-sex option[value="' + row['sex'] + '"]').prop('selected', 'selected');
                    $('#mm-realname').val(row['realname']);
                    $('#mm-certificates_type option[value="' + row['certificates_type'] + '"]').prop('selected', 'selected');
                    $('#mm-person_no').val(row['person_no']);
                    $('#mm-birthday').val(row['birthday']);
                    $('#mm-tel').val(row['tel']);
                });

                // 删除按钮事件
                $(customer_table).on('click', '[data-index].js_delete', function (e) {
                    e.preventDefault();
                    var data = customer_table.bootstrapTable('getData');
                    var delete_index = $(this).data('index');
                    // console.log('delete', data[delete_index]);

                    Layer.confirm('确认删除此客人', {
                        icon : 3,
                        title: '提示'
                    }, function (x) {
                        var new_data = [];
                        $.each(data, function (i) {
                            if (i != delete_index) {
                                new_data.push(data[i]);
                            }
                        });
                        // console.log(new_data);
                        customer_table.bootstrapTable('load', {total: new_data.length, rows: new_data});

                        new_data = new_data.length == 0 ? '' : new_data;
                        $('#m-customer_data').val(JSON.stringify(new_data));
                        Layer.close(x);
                    });
                });

                //保存编辑的入住客人信息
                $('#js_MSubmit').click(function () {
                    $('#customerModal').modal('hide');
                    var data = customer_table.bootstrapTable('getData');
                    var index = $('#mm-index').val();
                    // console.log(index)
                    if (index == -1) {
                        index = data.length;
                        data.push({
                            'index'            : data.length,
                            'sex'              : $('#mm-sex').val(),
                            'realname'         : $('#mm-realname').val(),
                            'certificates_type': $('#mm-certificates_type').val(),
                            'person_no'        : $('#mm-person_no').val(),
                            'birthday'         : $('#mm-birthday').val(),
                            'tel'              : $('#mm-tel').val()
                        });
                    } else {
                        data[index]['sex'] = $('#mm-sex').val();
                        data[index]['realname'] = $('#mm-realname').val();
                        data[index]['certificates_type'] = $('#mm-certificates_type').val();
                        data[index]['person_no'] = $('#mm-person_no').val();
                        data[index]['birthday'] = $('#mm-birthday').val();
                        data[index]['tel'] = $('#mm-tel').val();
                    }

                    customer_table.bootstrapTable('load', {total: data.length, rows: data});
                    // console.log(data);
                    $('#m-customer_data').val(JSON.stringify(data));
                });

                // 为表格绑定事件
                Table.api.bindevent(customer_table);

                $('#js_getMBirthday').click(function () {
                    if ($('#mm-person_no').val() == '') {
                        Layer.msg('证件号码不能为空');
                    } else {
                        var birthday = '';
                        var person_no = $('#mm-person_no').val();
                        if (person_no.length == 15) {
                            birthday = '19' + person_no.substr(6, 6);
                        } else if (person_no.length == 18) {
                            birthday = person_no.substr(6, 8);
                        }

                        birthday = birthday.replace(/(.{4})(.{2})/, '$1-$2-');

                        if (birthday == '') {
                            Layer.msg('读取出错');
                        } else {
                            $('#mm-birthday').val(birthday);
                        }
                    }
                });

                setTimeout(function () {
                    $('#js_addons .plupload-preview a.btn-trash').remove();
                }, 50);
                $('#js_operate-box button').on('click', function () {
                    var that = $(this);
                    var event = that.data('event');

                    $('#editModal #m-event').val(event);
                    switch (event) {
                        case 'edit-linkman':
                            $('#editModal').modal('show');
                            $('#editModal #editModalLabel').text('改患者信息');
                            $('#m-edit-linkman').show();
                            $('#m-edit-date').hide();
                            $('#m-edit-room').hide();
                            $('#m-edit-addons').hide();
                            $('#m-edit-customer').hide();
                            break;
                        case 'edit-room':
                            $('#editModal').modal('show');
                            $('#editModal #editModalLabel').text('更换床位');
                            $('#m-edit-linkman').hide();
                            $('#m-edit-date').hide();
                            $('#m-edit-room').show();
                            $('#m-edit-addons').hide();
                            $('#m-edit-customer').hide();
                            break;
                        case 'edit-date':
                            $('#editModal').modal('show');
                            $('#editModal #editModalLabel').text('改住院信息');
                            $('#m-edit-linkman').hide();
                            $('#m-edit-date').show();
                            $('#m-edit-room').hide();
                            $('#m-edit-addons').hide();
                            $('#m-edit-customer').hide();
                            break;
                        case 'edit-addons':
                            $('#editModal').modal('show');
                            $('#editModal #editModalLabel').text('改附件');
                            $('#m-edit-linkman').hide();
                            $('#m-edit-date').hide();
                            $('#m-edit-addons').show();
                            $('#m-edit-room').hide();
                            $('#m-edit-customer').hide();
                            break;
                        case 'edit-customer':
                            $('#editModal').modal('show');
                            $('#editModal #editModalLabel').text('改同住客人');
                            $('#m-edit-linkman').hide();
                            $('#m-edit-date').hide();
                            $('#m-edit-addons').hide();
                            $('#m-edit-room').hide();
                            $('#m-edit-customer').show();
                            break;
                        case 'add-items':
                            $('#additemsModal').modal('show');
                            break;
                    }
                });

                $('#editModal .btn-primary').on('click', function (e) {
                    var that = $(this);
                    var event = $('#editModal #m-event').val();
                    var id = $('#c-id').val();
                    var remarks = $('#m-remarks').val();

                    var params = {};
                    params['id'] = id;
                    params['items_id'] = that.data('items_id');
                    params['event'] = event;
                    params['disease_id'] = $('#m-disease_id').val();
                    params['sex'] = $('#m-sex').val();
                    params['realname'] = $('#m-realname').val();
                    params['certificates_type'] = $('#m-certificates_type').val();
                    params['person_no'] = $('#m-person_no').val();
                    params['birthday'] = $('#m-birthday').val();
                    params['nation'] = $('#m-nation').val();
                    params['tel'] = $('#m-tel').val();
                    params['order_remarks'] = $('#m-order_remarks').val();
                    params['addons'] = $('#m-addons').val();
                    params['check_in_time'] = $('#m-check_in_time').val();
                    params['check_out_time'] = $('#m-check_out_time').val();
                    params['days'] = $('#m-days').val();
                    params['order_invalid_memo'] = remarks;
                    params['customer_data'] = $('#m-customer_data').val();

                    if (event === 'edit-room') {
                        let roomInfo = $('#m-room-info').val().split(',');
                        if (roomInfo.length < 2) {
                            return Layer.msg('请选择');
                        }
                        params['room_info_id'] = roomInfo[0];
                        params['room_type_id'] = roomInfo[1];
                        params['room_info_text'] = $.trim($('#m-room-info option:selected').text());
                    }

                    Backend.api.ajax({
                        url : 'pms/Pmsroomstatus/ajax_update_order_info',
                        data: params
                    }, function (d) {
                        $('#editModal').modal('hide');
                        // setTimeout(function () {
                        if (event === 'go-order' || event === 'cancel') {
                            parent.window.G.fun.ReloadOrderTable();
                        } else if (event === 'edit-room' || event === 'edit-date' || event === 'edit-linkman') {
                            parent.window.location.reload();
                            parent.window.G.fun.Reload();
                        } else {
                            G.fun.Reload();
                        }
                    });
                });

                //打开弹窗后重置表单
                $('#additemsModal').on('show.bs.modal', function (e) {
                    $('input[name="ai_type"]').prop('checked', '');
                    $('input[name="ai_type"]').eq(0).prop('checked', 'checked');
                    $('#ai-items_id').empty().append('<option value="0">请选择</option>');
                    $.each(roomitems_data, function (i) {
                        var row = roomitems_data[i];
                        $('#ai-items_id').append('<option value="' + row['id'] + '">' + row['name'] + '(单价:￥' + row['price'] + ')</option>');
                    });
                    $('#ai-num option').prop('selected', '');
                    $('#ai-num option').eq(0).prop('selected', 'selected');
                });

                $('input[name="ai_type"]').click(function () {
                    var that = $(this);
                    var data = null;
                    switch (that.val()) {
                        case 'items':
                            data = roomitems_data;
                            break;
                        case 'services':
                            data = roomservicesitems_data;
                            break;
                    }
                    $('#ai-items_id').empty().append('<option value="0">请选择</option>');
                    $.each(data, function (i) {
                        var row = data[i];
                        $('#ai-items_id').append('<option value="' + row['id'] + '">' + row['name'] + '(单价:￥' + row['price'] + ')</option>');
                    });
                    $('#ai-num option').prop('selected', '');
                    $('#ai-num option').eq(0).prop('selected', 'selected');
                });

                $('#js_AISubmit').click(function () {
                    if ($('#ai-items_id').val() == 0) {
                        Layer.msg('请选择一个消费项目');
                    } else {
                        var order_id = $('#c-id').val();
                        var type = $('input[name="ai_type"]:checked').val();
                        var items_id = $('#ai-items_id').val();
                        var num = $('#ai-num').val();
                        var addons = $('#ai-addons').val();
                        var remarks = $('#ai-remarks').val();

                        Backend.api.ajax({
                            url : 'pms/Pmsroomstatus/ajax_add_order_items',
                            data: {
                                order_id: order_id,
                                type    : type,
                                items_id: items_id,
                                num     : num,
                                addons  : addons,
                                remarks : remarks
                            }
                        }, function (d) {
                            $('#additemsModal').modal('hide');
                            setTimeout(function () {
                                G.fun.Reload();
                            }, 1000);
                        });
                    }
                });

                Form.api.bindevent($('form[role=form]'));
                Form.api.bindevent($('form[role=modalform]'));
                Form.api.bindevent($('form[role=customerform]'));
                Form.api.bindevent($('form[role=itemsform]'));
            },
            pay         : function () {
                var order_id = $('#c-order_id').val();

                $('#c-pay_type').change(function () {
                    if ($(this).val() == '退押金') {
                        $('#c-money').prop('placeholder', '选择"退押金"时，金额请输入负数!');
                    } else {
                        $('#c-money').prop('placeholder', '');
                    }
                })

                // 初始化表格参数配置
                Table.api.init({
                    extend: {
                        index_url: 'pms/pmsroomstatus/ajax_get_order_payment?order_id=' + order_id,
                        table    : 'pms_order_payment'
                    }
                });

                var paied_table = $('#paied_table');

                //当表格数据加载完成时
                paied_table.on('load-success.bs.table', function (e, data) {
                    $('.js_cancel').on('click', function () {
                        var that = $(this);
                        var id = that.data('id');

                        $('#cancelModal').modal('show');
                        $('#js_submitCancel').data('id', id);
                    });
                });

                // 初始化表格
                paied_table.bootstrapTable({
                    url         : $.fn.bootstrapTable.defaults.extend.index_url,
                    pk          : 'id',
                    search      : false,
                    showToggle  : false,
                    showExport  : false,
                    commonSearch: false,
                    showColumns : false,
                    pagination  : false,
                    columns     : [
                        [
                            {field: 'id', title: __('id')},
                            {
                                field: 'pay_type', title: __('付款类型'), formatter: function (value, row, index) {
                                    return '<a href="javascript:;" data-toggle="tooltip" data-original-title="' + row.remarks + '">' + value + '</a>';
                                }
                            },
                            {field: 'money', title: __('金额')},
                            {field: 'addons', title: __('附件'), events: Table.api.events.image, formatter: Table.api.formatter.images, operate: false, align: 'left'},
                            {field: 'state', title: __('状态'), searchList: {'0': __('正常'), '2': __('已作废')}, formatter: Table.api.formatter.flag},
                            {field: 'createtime', title: __('创建时间'), operate: false, addclass: 'datetimerange', formatter: Table.api.formatter.datetime},
                            {
                                field: 'operate', title: __('Operate'), formatter: function (value, row, index) {
                                    var html = row['state'] == 0 ? '<a href="javascript:;" class="btn btn-xs btn-danger js_cancel" data-id="' + row['id'] + '"><i class="fa fa-trash"></i> 作废</a>' : '';
                                    return html;
                                }
                            }
                        ]
                    ]
                });

                // 为表格绑定事件
                Table.api.bindevent(paied_table);
                Form.api.bindevent($('form[role=form]'));

                $('#js_submitCancel').click(function () {
                    var that = $(this);
                    var id = that.data('id');
                    var remarks = $('#c-cancelRemarks').val();

                    if (remarks.length == 0) {
                        Layer.msg('请录入作废理由')
                    } else {
                        Layer.confirm('确定作废这一记录', {
                            icon : 3,
                            title: '提示'
                        }, function (index) {
                            Backend.api.ajax({
                                url : 'pms/Pmsroomstatus/ajax_cancel_payment',
                                data: {id: id, remarks: remarks}
                            }, function (d) {
                                Layer.close(index);
                                setTimeout(function () {
                                    window.location.reload();
                                }, 1000);
                            });
                        });
                    }
                });
            },
            checkout    : function () {
                var order_id = $('#c-order_id').val();

                // 初始化表格参数配置
                Table.api.init({
                    extend: {
                        index_url: 'pms/pmsroomstatus/ajax_get_project?order_id=' + order_id,
                        table    : 'pms_order_payment'
                    }
                });

                var bill_table = $('#bill_table');

                //当表格数据加载完成时
                bill_table.on('load-success.bs.table', function (e, data) {
                    $('#total_income b').text(data['total_income']);
                    $('#total_expenditure b').text(data['total_expenditure']);
                    $('#total_diff b').text(data['total_diff']);
                    $('#c-total_diff').val(data['total_diff']);

                    if (data['total_diff'] != 0) {
                        Layer.msg('注意：收支未平，可能造成出院后浮盈或浮亏');
                    }
                });

                // 初始化表格
                bill_table.bootstrapTable({
                    url         : $.fn.bootstrapTable.defaults.extend.index_url,
                    pk          : 'id',
                    search      : false,
                    showToggle  : false,
                    showExport  : true,
                    commonSearch: false,
                    showColumns : false,
                    pagination  : false,
                    columns     : [
                        [
                            {
                                field: 'index', title: __('#'), formatter: function (valur, row, index) {
                                    return index + 1;
                                }
                            },
                            {field: 'name', title: __('项目'), align: 'left', width: '40%'},
                            {
                                field: 'money', title: __('金额'), formatter: function (value, row, index) {
                                    return value >= 0 ? '<span class="label label-success">￥' + value + '</span>' : '<span class="label label-danger">￥' + value + '</span>';
                                }
                            },
                            {field: 'createtime', title: __('创建时间'), operate: false, addclass: 'datetimerange', formatter: Table.api.formatter.datetime},
                            {field: 'creator_nickname', title: __('操作员'), operate: false}
                        ]
                    ]
                });

                $('#js_Checkout').click(function () {
                    var total_diff = $('#c-total_diff').val();
                    var order_id = $('#c-order_id').val();

                    var msg = total_diff == 0 ? '确认出院' : '注意：收支未平，可能造成出院后浮盈或浮亏，确定出院吗？';
                    Layer.confirm(msg, {
                        icon : 3,
                        title: '提示'
                    }, function (index) {
                        Backend.api.ajax({
                            url : 'pms/Pmsroomstatus/ajax_checkout',
                            data: {order_id: order_id}
                        }, function (d) {
                            Layer.close(index);
                            setTimeout(function () {
                                parent.window.G.fun.Reload();
                            }, 1000);
                        });
                    });
                });

                // 为表格绑定事件
                Table.api.bindevent(bill_table);
            },
            api         : {
                bindevent: function () {
                    Form.api.bindevent($('div[role=tabpanel]'));
                }
            }
        };
        G.fun = Controller.fun;


        return Controller;
    });
